<template>
  <div class="app-container h-flex">
    <div class="tree-box app-container__left">
      <div class="type-title" @click="listQuery.deptId='';search()">部门</div>
      <el-tree
        ref="tree_box"
        :data="deptTreeData"
        node-key="id"
        icon-class="el-icon-arrow-right"
        :expand-on-click-node="false"
        default-expand-all
        :props="defaultDeptProps"
        @node-click="nodeClick" />
    </div>
    <div
      ref="tree_box_right"
      class="h-flex-elastic v-flex overflow-hidden app-container__right">
      <filter-form :form="listQuery" :data="filterData" @search="search" @addForm="addForm">
        <el-button
          v-permission-button="'ITPS-DELETE'"
          class="form__button icon-red"
          size="mini"
          type="primary"
          icon="el-icon-delete"
          @click="deleteDatas">
          删除
        </el-button>
        <!-- <el-button
          class="form__button icon-green"
          size="mini"
          type="success">
          <svg-icon icon-class="import" class-name="svg-import" />导入
        </el-button> -->
      </filter-form>
      <div ref="main" class="v-flex-elastic">
        <base-table
          ref="table"
          :height="height"
          :loading="listLoading"
          :data="tableData"
          :columns="columns"
          :show-index="false"
          show-filter-column
          show-selection
          operaton-width="150px"
          @view="view"
          @updateForm="updateForm"
          @deleteData="deleteData"
          @selection-change="handleSelectionChange">
          <template slot="status" slot-scope="{row,$index}">
            <el-switch v-model="row.status" :active-value="1" :inactive-value="0" @change="enable(row,$index)" />
          </template>
          <el-button
            slot="operations"
            slot-scope="{row, $index}"
            size="mini"
            class="td-btn-operation"
            @click="certificate(row, $index)">证书</el-button>
        </base-table>
      </div>
      <div class="page-box">
        <pagination
          :total="total"
          :page.sync="listQuery.page"
          :size.sync="listQuery.size"
          @pagination="getList" />
      </div>

      <base-dialog
        class="worker-dialog"
        :visible.sync="dialog1.visible"
        :title="dialog1.title"
        :loading="dialog1.loading"
        :disabled="dialog1.disabled"
        @open="beforeOpenDialog1"
        @updateData="updateData">
        <el-form
          ref="dataForm"
          :rules="rules"
          :model="temp"
          :disabled="dialog1.disabled"
          label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="姓名" prop="staffName">
                <el-input v-model="temp.staffName" />
              </el-form-item>
              <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="temp.sex">
                  <el-radio :label="1">男</el-radio>
                  <el-radio :label="0">女</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="民族" prop="ethnic">
                <el-select v-model="temp.ethnic">
                  <el-option
                    v-for="item in ethnicList"
                    :key="item.id"
                    :label="item.dicKey"
                    :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item style="margin-bottom:0;">
                <el-upload
                  class="avatar-uploader"
                  action="/dfs/upload"
                  accept="image/*"
                  :show-file-list="false"
                  :before-upload="beforeAvatarUpload">
                  <img
                    v-if="returnImageUrl"
                    :src="imageUrl"
                    class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon" />
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="部门" prop="deptId">
                <select-tree
                  ref="tree_box1"
                  v-model="temp.deptId"
                  :options="deptTreeData"
                  :props="defaultProps" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="职务"
                prop="position">
                <el-input v-model="temp.position" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="工种" prop="wtid">
                <el-select v-model="temp.wtid">
                  <el-option
                    v-for="item in professionList"
                    :key="item.id"
                    :label="item.wtName"
                    :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="工作证号"
                prop="jobCardNum">
                <el-input v-model="temp.jobCardNum" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="工作电话" prop="phoneNum">
                <el-input v-model="temp.phoneNum" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="技能等级"
                prop="skillLevel">
                <el-select v-model="temp.skillLevel">
                  <el-option
                    v-for="item in skillLevelList"
                    :key="item.id"
                    :label="item.dicKey"
                    :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="手机号码" prop="mobileNum">
                <el-input v-model="temp.mobileNum" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="启用">
                <el-switch v-model="temp.status" :active-value="1" :inactive-value="0" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </base-dialog>
      <!-- <el-dialog
        :title="textMap[dialogStatus]"
        :visible.sync="dialogFormVisible"
        :close-on-click-modal="false">
        <div slot="footer" class="dialog-footer">
          <el-button
            v-if="!disabled"
            type="primary"
            @click="dialogStatus==='create'?addData():updateData()">
            保存
          </el-button>
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
        </div>
      </el-dialog> -->
      <base-dialog
        class="work-certificate-dialog"
        fullscreen
        close-on-press-escape
        :visible.sync="dialog.visible"
        :title="dialog.title"
        :loading="dialog.loading"
        @open="beforeOpenDialog"
        @updateData="updateData1">
        <div class="form-table">
          <div class="form-table-head">
            <div class="form-table-row">
              <div class="form-table-col" style="width:50px;">序号</div>
              <div class="form-table-col">证书编号</div>
              <div class="form-table-col">证书类型</div>
              <div class="form-table-col">证书等级</div>
              <div class="form-table-col">考试日期</div>
              <div class="form-table-col">分数</div>
              <div class="form-table-col">发证日期</div>
              <div class="form-table-col">有效期</div>
              <div class="form-table-col" style="flex: 1;">备注</div>
              <div class="form-table-col" style="width:27px;" />
            </div>
          </div>
          <div class="form-table-body">
            <el-form ref="dataForm1" :model="dialog.form">
              <transition-group name="list-transition">
                <div v-for="(item, index) in dialog.form.certificateList" :key="item.key||index" class="form-table-row list-transition-item">
                  <div class="form-table-col" style="width:50px;line-height:36px;">{{ index + 1 }}</div>
                  <div class="form-table-col">
                    <el-form-item :prop="`certificateList.${index}.certificateCode`" :rules="dialog.rules.certificateCode">
                      <el-input v-model="item.certificateCode" clearable />
                    </el-form-item>
                  </div>
                  <div class="form-table-col">
                    <el-form-item :prop="`certificateList.${index}.certificateType`" :rules="dialog.rules.certificateType">
                      <el-select v-model="item.certificateType" clearable>
                        <el-option
                          v-for="child in certificateTypes"
                          :key="child.id"
                          :label="child.dicKey"
                          :value="child.id" />
                      </el-select>
                    </el-form-item>
                  </div>
                  <div class="form-table-col">
                    <el-form-item :prop="`certificateList.${index}.certificateLevel`" :rules="dialog.rules.certificateLevel">
                      <el-select v-model="item.certificateLevel" clearable>
                        <el-option
                          v-for="child in certificateLevels"
                          :key="child.id"
                          :label="child.dicKey"
                          :value="child.id" />
                      </el-select>
                    </el-form-item>
                  </div>
                  <div class="form-table-col">
                    <el-form-item :prop="`certificateList.${index}.examDate`" :rules="dialog.rules.examDate">
                      <el-date-picker v-model="item.examDate" value-format="timestamp" />
                    </el-form-item>
                  </div>
                  <div class="form-table-col">
                    <el-form-item :prop="`certificateList.${index}.score`" :rules="dialog.rules.score">
                      <el-input v-model="item.score" clearable />
                    </el-form-item>
                  </div>
                  <div class="form-table-col">
                    <el-form-item :prop="`certificateList.${index}.issueDate`" :rules="dialog.rules.issueDate">
                      <el-date-picker v-model="item.issueDate" value-format="timestamp" />
                    </el-form-item>
                  </div>
                  <div class="form-table-col">
                    <el-form-item :prop="`certificateList.${index}.expiryDate`" :rules="dialog.rules.expiryDate">
                      <el-date-picker v-model="item.expiryDate" value-format="timestamp" />
                    </el-form-item>
                  </div>
                  <div class="form-table-col" style="flex:1;">
                    <el-form-item :prop="`certificateList.${index}.memo`" :rules="dialog.rules.memo">
                      <el-input v-model="item.memo" type="textarea" :rows="1" />
                    </el-form-item>
                  </div>
                  <div class="form-table-col" style="width:27px;">
                    <el-button
                      title="删除"
                      size="mini"
                      icon="el-icon-delete"
                      @click="deleteCertificate(index)" />
                  </div>
                </div>
              </transition-group>
            </el-form>
          </div>
          <div class="form-table-add">
            <el-button
              title="添加"
              size="mini"
              icon="el-icon-plus"
              @click="addCertificate" />
          </div>
        </div>
      </base-dialog>
    </div>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { upload } from '@/api/dsc/main'
import { getListTree } from '@/api/dsc/system/department'
import { getList, saveOrUpdate, deleteById, deleteByIds } from '@/api/dsc/system/worker'
import { getListByTypeCode } from '@/api/dsc/system/dictionary/general'
import { getListAll } from '@/api/dsc/system/dictionary/work-type'
import { Message } from 'element-ui'
import { tableMixin } from '@/utils/public'
export default {
  name: 'DscWorker',
  mixins: [tableMixin],
  data() {
    return {
      // 部门树
      deptTreeData: [],
      defaultDeptProps: {
        children: 'children',
        label: 'label'
      },
      // 数据默认字段
      defaultProps: {
        parent: 'parentId', // 父级唯一标识
        value: 'id', // 唯一标识
        label: 'label', // 标签显示
        children: 'children' // 子级
      },

      // imageUrl: '', // 显示的图片路径
      returnImageUrl: '', // 上传返回的图片路径
      // 部门下拉选项
      optionsDept: [],
      treeHeight: 0, // tree高度
      height: 0, // table高度
      tableData: [], // 表格数据
      columns: [
        { label: '姓名', prop: 'staffName' },
        { label: '工作证号', prop: 'jobCardNum' },
        { label: '性别', prop: 'sex', formatter: row => row.sex === 1 ? '男' : '女' },
        { label: '部门', prop: 'deptName' },
        { label: '职务', prop: 'position' },
        { label: '工种', prop: 'professionName' },
        { label: '技能等级', prop: 'skillLevelName' },
        { label: '工作电话', prop: 'phoneNum' },
        { label: '启用', prop: 'status', template: true }
      ],
      listQuery: {// 搜索条件
        deptId: '',
        keyName: '',
        page: 1,
        size: 20
      },
      filterData: {
        keyName: {
          key: 'keyName',
          type: 'input',
          placeholder: '名称、职务'
        }
      },
      total: 0,
      textMap: {
        update: '编辑',
        view: '查看',
        create: '添加'
      },
      dialogFormVisible: false, // 弹窗开关
      dialogStatus: '', // 弹窗类型（添加、查看、编辑）
      dialog1: {
        visible: false,
        title: '',
        loading: false,
        disabled: false
      },
      temp: {},
      tempForm: {// 弹窗表单
        id: null,
        staffName: '',
        sex: 1,
        ethnic: null,
        portraitPath: null,
        deptId: null,
        position: null,
        wtid: null,
        jobCardNum: null,
        phoneNum: null,
        skillLevel: null,
        mobileNum: null,
        status: 1,
        delFlag: 0
      },
      rowIndex: null,
      rules: {},
      rulesModel: {
        staffName: [{ required: true, message: '必填', trigger: 'blur' }, { max: 20, message: '小于20个字符', trigger: 'blur' }],
        position: [{ max: 11, message: '小于11个字符', trigger: 'blur' }],
        jobCardNum: [{ required: true, message: '必填', trigger: 'blur' }, { max: 20, message: '小于20个字符', trigger: 'blur' }],
        phoneNum: [{ max: 11, message: '小于11个字符', trigger: 'blur' }],
        mobileNum: [{ max: 11, message: '小于11个字符', trigger: 'blur' }],
        deptId: [{ required: true, message: '必选', trigger: 'blur' }]
      },
      listLoading: false,
      disabled: false, // 是否禁止表单操作
      ethnicList: [], // 民族
      professionList: [], // 工种
      skillLevelList: [], // 技能等级
      multipleSelection: [], // 选择行的复选框
      dialog: {
        title: '',
        visible: false,
        loading: false,
        form: [],
        rules: {}
      },
      certificateTypes: [],
      certificateLevel: []
    }
  },
  computed: {
    imageUrl() {
      return (
        process.env.VUE_APP_BASE_API +
        '/dfile/file/download?fileUrl=' +
        this.returnImageUrl +
        '&access_token=' +
        getToken()
      )
    }
  },
  created() {
    this.temp = Object.assign({}, this.tempForm)
    getListAll({ }).then(response => {
      this.professionList = response.data
    })
    getListByTypeCode({ typeCode: this.publicConfig['002'] }).then(response => {
      this.skillLevelList = response.data
    })
    getListByTypeCode({ typeCode: this.publicConfig['008'] }).then(response => {
      this.ethnicList = response.data
    })
    getListByTypeCode({ typeCode: this.publicConfig['037'] }).then(response => {
      this.certificateTypes = response.data
    })
    getListByTypeCode({ typeCode: this.publicConfig['038'] }).then(response => {
      this.certificateLevels = response.data
    })
    this.getListTree()
    this.search()
  },
  methods: {
    // 查询部门树
    getListTree() {
      getListTree({}).then(response => {
        this.deptTreeData = response.data
      })
    },
    // 查询列表
    getList() {
      this.listLoading = true
      getList(this.listQuery).then(response => {
        this.tableData = response.data.records
        this.total = response.data.total
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    // 点击tree节点回调
    nodeClick(data) {
      this.listQuery.deptId = data.id
      this.search()
    },
    // 搜索
    search() {
      this.listQuery.page = 1
      this.getList()
    },
    // 添加
    addForm() {
      // this.disabled = false
      this.temp = Object.assign({}, this.tempForm)
      this.returnImageUrl = ''
      // this.dialogStatus = 'create'
      // this.dialogFormVisible = true
      this.rules = Object.assign({}, this.rulesModel)
      this.dialog1 = Object.assign({}, this.dialog1, {
        visible: true,
        title: '添加',
        loading: false,
        disabled: false
      })
    },
    // 添加数据
    // addData() {
    //   this.validate().then(() => {
    //     this.saveOrUpdate(this.temp, 1)
    //   })
    // },
    // 查看
    view(row) {
      // this.disabled = true
      this.temp = Object.assign({}, this.tempForm) // copy obj
      this.temp = Object.assign(this.temp, row) // copy obj
      // this.dialogStatus = 'view'
      this.rules = {}
      // this.dialogFormVisible = true
      this.dialog1 = Object.assign({}, this.dialog1, {
        visible: true,
        title: '查看',
        loading: false,
        disabled: true
      })
    },
    // 编辑
    updateForm(row, $index) {
      // this.disabled = false
      this.rowIndex = $index
      this.temp = Object.assign({}, this.tempForm) // copy obj
      this.temp = Object.assign(this.temp, row) // copy obj
      this.returnImageUrl = this.temp.portraitPath
      // this.dialogStatus = 'update'
      this.rules = Object.assign({}, this.rulesModel)
      // this.dialogFormVisible = true
      this.dialog1 = Object.assign({}, this.dialog1, {
        visible: true,
        title: '编辑',
        loading: false,
        disabled: false
      })
    },
    // 编辑数据
    updateData() {
      this.validate().then(() => {
        this.saveOrUpdate(this.temp, 2)
      })
    },
    // type 1 添加，2 编辑
    saveOrUpdate(params, type) {
      this.listLoading = true
      const param = Object.assign({}, params)
      param.portraitPath = this.returnImageUrl
      saveOrUpdate(param).then(response => {
        if (this.dialog.title === '添加') {
          this.tableData.unshift(response.data)
          this.total++
        } else {
          Object.assign(this.tableData[this.rowIndex], response.data)
        }
        this.dialog.visible = false
        this.listLoading = false
        this.notifiySuccess('保存成功')
      }).catch(() => {
        this.listLoading = false
      })
    },
    beforeOpenDialog1() {
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 删除
    deleteData(row, $index) {
      this.confirmBox('确定删除?').then(() => {
        deleteById(row.id).then(response => {
          this.notifiySuccess('删除成功!')
          // this.tableData.splice($index, 1)
          this.total--
          this.$refs.tree_box.remove(row.id)
          this.search()
        })
      }).catch(() => {

      })
    },
    // 启用、停用
    enable(row, $index) {
      this.rowIndex = $index
      this.saveOrUpdate(row, 2)
    },
    // 批量删除
    deleteDatas() {
      let ids = ''
      for (const i of this.multipleSelection) {
        ids += ',' + i.id
      }
      ids = ids.substring(1)
      if (!ids) {
        Message({
          message: '请至少选择一条数据',
          type: 'error',
          duration: 3 * 1000
        })
        return
      }
      this.confirmBox('确定删除?').then(() => {
        deleteByIds({ ids: ids }).then(response => {
          this.notifiySuccess('删除成功!')
          this.search()
        })
      }).catch(() => {

      })
    },
    // 选择行复选框
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    // 全选、反选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    beforeAvatarUpload(file) {
      const param = new FormData()
      param.append('file', file)
      upload(param).then(response => {
        this.returnImageUrl = response.data
      })
      return false
    },
    // 添加证书
    certificate(row, index) {
      this.rowIndex = index
      const dialog = {
        title: '添加证书',
        visible: true,
        loading: false,
        form: JSON.parse(JSON.stringify(row))
      }
      !dialog.form.certificateList ? dialog.form.certificateList = [] : ''
      this.dialog = Object.assign(this.dialog, dialog)
    },
    beforeOpenDialog() {
      this.$nextTick(() => {
        this.$refs.dataForm1.clearValidate()
      })
    },
    updateData1() {
      this.dialog.loading = true
      this.$refs.dataForm1.validate(valid => {
        if (valid) {
          saveOrUpdate(this.dialog.form).then(response => {
            Object.assign(this.tableData[this.rowIndex], response.data)
            this.dialog.visible = false
            this.dialog.loading = false
            this.notifiySuccess('保存成功')
          }).catch(() => {
            this.dialog.loading = false
          })
        }
      })
    },
    addCertificate() {
      this.dialog.form.certificateList.push({
        key: new Date().getTime()
      })
    },
    deleteCertificate(index) {
      this.confirmBox('确定删除?').then(() => {
        this.dialog.form.certificateList.splice(index, 1)
      })
    }
  }
}
</script>
<style scoped>
  .svg-import{
    font-size: 11px;
    margin-right: 9px;
  }
</style>
<style lang="scss">
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    line-height: 150px;
    text-align: center;
  }
  .avatar {
    width: 150px;
    height: 150px;
    display: block;
  }
  .work-certificate-dialog {
    .el-dialog__body{
      max-height: calc(100vh - 103px);
      height: calc(100vh - 103px);
    }
    .form-table{
      .form-table-head{
        padding: 0 30px;
      }
      .form-table-body{
        height: calc(100vh - 215px);
        overflow-y: auto;
        position: relative;
      }
      .form-table-row{
        display: flex;
        margin-bottom: 15px;
        .form-table-col{
          width: 150px;
          text-align: center;
          padding: 5px 5px 0;
          &.is-required::before {
            content: "*";
            width: 5px;
            height: 5px;
            margin-right: 5px;
            color: red;
          }
          .el-textarea__inner{
            min-height: 36px !important;
          }
        }
        .el-form-item{
          margin-bottom: 0;
        }
      }
      .list-transition-leave-active{
        width: calc(100% - 60px);
      }
      .el-button{
        border: 0;
        padding: 10px;
        font-size: 16px;
        background: none;
      }
      .form-table-add{
        display: inline-block;
        width: 50px;
        margin-left: 30px;
        text-align: center;
        .el-icon-plus{
          font-size: 26px;
        }
      }
    }
  }
</style>
